import { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import type { MirrorWebsiteFile } from "@common/spider-types.ts";
import type { ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import semver from "semver";
import path from "@/framework/util/path.ts";

export abstract class MariadbMirror extends BaseEnvMirror {
  protected getDownloadList0(files: MirrorWebsiteFile[]): ToolInstallVersionItem[] | Promise<ToolInstallVersionItem[]> {
    const versionList: ToolInstallVersionItem[] = [];
    for (const it of files) {
      if (it.type === "dir" && it.name.startsWith("mariadb-")) {
        const [, version] = it.name.split("-");
        // https://xxx.com/mariadb/mariadb-12.1.0/winx64-packages/mariadb-12.1.0-winx64.zip
        const downloadUrl = `${this.url}${it.name}/winx64-packages/${it.name}-winx64.zip`;
        versionList.push({
          id: it.name,
          name: path.basename(downloadUrl),
          version: version,
          url: downloadUrl,
          date: it.date,
          size: it.size,
        });
      }
    }

    try {
      versionList.sort((a, b) => semver.compare(b.version, a.version));
    } catch (e) {
      // ignored
    }

    return versionList;
  }
}

export class MariadbTsinghuaMirror extends MariadbMirror {
  constructor() {
    super({
      id: "mariadb.tsinghua",
      name: "清华大学",
      url: "https://mirrors.tuna.tsinghua.edu.cn/mariadb/",
      website: "https://mirrors.tuna.tsinghua.edu.cn",
    });
  }
}

export class MariadbAliyunMirror extends MariadbMirror {
  constructor() {
    super({
      id: "mariadb.aliyun",
      name: "阿里云",
      url: "https://mirrors.aliyun.com/mariadb/",
      website: "https://mirrors.aliyun.com/",
    });
  }
}

export class MariadbNeusoftMirror extends MariadbMirror {
  constructor() {
    super({
      id: "mariadb.neusoft",
      name: "大连东软",
      url: "https://mirrors.neusoft.edu.cn/mariadb/",
      website: "https://mirrors.neusoft.edu.cn/",
    });
  }
}

export class MariadbNyistMirror extends MariadbMirror {
  constructor() {
    super({
      id: "mariadb.nyist",
      name: "南洋理工",
      url: "https://mirror.nyist.edu.cn/mariadb/",
      website: "https://mirror.nyist.edu.cn/",
    });
  }
}

export class MariadbVhostMirror extends MariadbMirror {
  constructor() {
    super({
      id: "mariadb.offical",
      name: "mariadb.org",
      url: "https://vn-mirrors.vhost.vn/mariadb/",
      website: "https://mariadb.org/",
    });
  }
}
